import Vue from "vue"
import qs from "qs"
import axios from "axios"
import store from "../store/index.js"

let proce = ""
// 开发环境
if (process.env.NODE_ENV == "development") {
  Vue.prototype.$pre = "http://localhost:3000"
  proce = "http://localhost:8080"
}
// 生产环境
if (process.env.NODE_ENV == "production") {
  Vue.prototype.$pre = ""
  proce = "http://localhost:3000"
}

// 请求拦截器
axios.interceptors.request.use((config) => {
  if (config.url != "/api/userlogin") {
    config.headers.authorization = store.state.userInfo.token
  }

  return config
})
// 响应拦截器
axios.interceptors.response.use((res) => {
  console.group("本次请求的地址：" + res.config.url)
  console.log(res)
  console.groupEnd("打印结束")
  if (res.data.msg == "登录已过期或访问权限受限") {
    window.location = proce + "/#/login"
  }

  return res
})

/* 
    get请求
*/
export const get = (url, params = {}) => {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    }).then(res => {
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}

/* 
    post请求
*/
export const post = (url, params = {}, isFile = false) => {
  let data = null

  if (isFile) {
    data = new FormData()
    for (let i in params) {
      data.append(i, params[i])
    }
  } else {
    data = qs.stringify(params)
  }

  return new Promise((resolve, reject) => {
    axios.post(url, data).then(res => {
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}